package gateway

import (
	"bufio"
	"fmt"
	"os"
	"strings"

	"github.com/toolkits/file"
)

func FetchGateway() string {
	var gw string

	if !file.IsExist("/proc/net/route") {
		return gw
	}

	f, err := os.Open("/proc/net/route")
	if err != nil {
		return gw
	}
	defer f.Close()

	scanner := bufio.NewScanner(f)
	for scanner.Scan() {
		fields := strings.Fields(scanner.Text())
		if len(fields) >= 3 && fields[1] == "00000000" {
			ip := make([]byte, 4)
			fmt.Sscanf(fields[2], "%2x%2x%2x%2x", &ip[3], &ip[2], &ip[1], &ip[0])
			gw = fmt.Sprintf("%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3])
			break
		}
	}

	return gw
}
